#!/usr/bin/env python3
"""
为工单表添加区域字段的迁移脚本
"""

import sqlite3
import os

def main():
    # 数据库文件路径
    db_path = '/home/gd/dispatch-system/backend/instance/dispatch_system.db'
    
    if not os.path.exists(db_path):
        print(f"数据库文件不存在: {db_path}")
        return
    
    try:
        # 连接数据库
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        
        # 检查字段是否已存在
        cursor.execute("PRAGMA table_info(work_orders)")
        columns = [column[1] for column in cursor.fetchall()]
        
        if 'area_id' not in columns:
            print("正在为工单表添加区域字段...")
            
            # 添加区域字段
            cursor.execute("""
                ALTER TABLE work_orders 
                ADD COLUMN area_id INTEGER REFERENCES areas(id)
            """)
            
            conn.commit()
            print("✓ 区域字段添加成功")
        else:
            print("区域字段已存在，跳过添加")
        
        conn.close()
        print("迁移完成")
        
    except Exception as e:
        print(f"迁移失败: {e}")
        if 'conn' in locals():
            conn.close()

if __name__ == '__main__':
    main()